﻿Imports System.IO
Imports System.Drawing.Printing

Module Variables
    Public ruta_programa As String = ""
    Public Conection_String As String '= "Data Source=localhost;Initial Catalog=SAE_3;User Id=Sergio;Password=mosco;"

    Public dsConfig As DataSet
    Public dsInfo As DataSet
    Public dsData As DataSet
    Public dsMetas As DataSet

    Public msg As New SuperMessageBox
    Public num As New Number_Input

    Dim documento As New PrintDocument
    Dim previo As New Windows.Forms.PrintPreviewDialog

    Dim iPedido As String = ""

    Public Function Valor_Config(ByVal tabla As String, ByVal key As String, Optional ByVal valor As String = "") As Object
        If dsConfig.Tables(tabla).Select("Concepto='" & key & "'").Count = 0 Then
            Dim fila As DataRow
            fila = dsConfig.Tables(tabla).NewRow
            fila(0) = key
            fila(1) = valor
            dsConfig.Tables(tabla).Rows.Add(fila)

            dsConfig.WriteXml(ruta_programa & "\Config.xml", XmlWriteMode.WriteSchema)
            dsConfig = New DataSet
            dsConfig.ReadXml(ruta_programa & "\Config.xml")
        End If

        Return CType(dsConfig.Tables(tabla).Select("Concepto='" & key & "'").GetValue(0), DataRow)(1)
    End Function

    Public Sub Comprime_Imagen(ByRef Imagen As Image, ByVal Ancho As Integer, ByVal Alto As Integer)
        Dim bmp As New Bitmap(Ancho, Alto)
        Dim g As Graphics = Graphics.FromImage(bmp)
        g.DrawImage(Imagen, 0, 0, Ancho, Alto)
        Imagen = bmp
    End Sub

    Public Function Get_Connection() As String
        Dim con As String = "Data Source="
        con += Valor_Config("SAE", "Servidor") & ";Initial Catalog="
        con += Valor_Config("SAE", "Base de Datos") & ";User Id="
        con += Valor_Config("SAE", "Usuario")

        Dim pwd As Object = Valor_Config("SAE", "Password")
        If Not pwd Is DBNull.Value Then con += ";Password=" & pwd

        'con += ";Trusted_Connection=True;"

        Conection_String = con
        Return con
    End Function

    Public Sub Carga_Datos(Optional ByVal crea_archivo As Boolean = False)
        If crea_archivo Then
            If File.Exists(ruta_programa & "\Datos.xml") Then
                File.Delete(ruta_programa & "\Datos.xml")
            End If
        End If

        If Not File.Exists(ruta_programa & "\Datos.xml") Then
            dsData = New DataSet

            Dim dtPagos As New DataTable("PAGOS")
            dtPagos.Columns.Add("CCLIE", GetType(String))
            dtPagos.Columns.Add("REFER", GetType(String))
            dtPagos.Columns.Add("IMPORTE", GetType(Double))
            dtPagos.Columns.Add("FECHA", GetType(String))
            dtPagos.Columns.Add("USUARIO", GetType(String))
            dtPagos.Columns.Add("TIPO", GetType(String))

            Dim dtFacturas As New DataTable("FACTURAS")
            dtFacturas.Columns.Add("CCLIE", GetType(String))
            dtFacturas.Columns.Add("FECHA", GetType(String))
            dtFacturas.Columns.Add("ENTREGA", GetType(String))
            dtFacturas.Columns.Add("REFER", GetType(String))
            dtFacturas.Columns.Add("USUARIO", GetType(String))
            dtFacturas.Columns.Add("SUBTOTAL", GetType(Double))
            dtFacturas.Columns.Add("IVA", GetType(Double))
            dtFacturas.Columns.Add("TOTAL", GetType(Double))
            dtFacturas.Columns.Add("TIPO", GetType(String))
            dtFacturas.Columns.Add("STATUS", GetType(Boolean))

            Dim dtProductos As New DataTable("PRODUCTOS")
            dtProductos.Columns.Add("REFER", GetType(String))
            dtProductos.Columns.Add("ITEM", GetType(Integer))
            dtProductos.Columns.Add("CANTIDAD", GetType(Double))
            dtProductos.Columns.Add("ARTICULO", GetType(String))
            dtProductos.Columns.Add("DESCRIPCION", GetType(String))
            dtProductos.Columns.Add("LINEA", GetType(String))
            dtProductos.Columns.Add("PRECIO", GetType(Double))
            dtProductos.Columns.Add("IVA", GetType(Double))
            dtProductos.Columns.Add("IMPORTE", GetType(Double))
            dtProductos.Columns.Add("TOTAL", GetType(Double))
            dtProductos.Columns.Add("STATUS", GetType(Boolean))

            dsData.Tables.Add(dtPagos)
            dsData.Tables.Add(dtFacturas)
            dsData.Tables.Add(dtProductos)

            dsData.WriteXml(ruta_programa & "\Datos.xml", XmlWriteMode.WriteSchema)
        End If

        dsData = New DataSet
        dsData.ReadXml(ruta_programa & "\Datos.xml")
    End Sub

    Public Sub Guarda_Datos()
        dsData.WriteXml(ruta_programa & "\Datos.xml", XmlWriteMode.WriteSchema)
        dsData = New DataSet
        dsData.ReadXml(ruta_programa & "\Datos.xml")

        dsConfig.WriteXml(ruta_programa & "\Config.xml", XmlWriteMode.WriteSchema)
        dsConfig = New DataSet
        dsConfig.ReadXml(ruta_programa & "\Config.xml")

        dsInfo.WriteXml(ruta_programa & "\Info.xml", XmlWriteMode.WriteSchema)
        dsInfo = New DataSet
        dsInfo.ReadXml(ruta_programa & "\Info.xml")

        '************************************************

        If Not dsMetas Is Nothing Then
            dsMetas.WriteXml(ruta_programa & "\Metas.xml", XmlWriteMode.WriteSchema)
            dsMetas = New DataSet
            dsMetas.ReadXml(ruta_programa & "\Metas.xml")
        End If
    End Sub

    Public Function Carga_Imagen(ByVal producto As String) As Image
        Dim bmp As Bitmap = Nothing

        If File.Exists(ruta_programa & "\Fotos\" & producto & ".png") Then
            bmp = New Bitmap(ruta_programa & "\Fotos\" & producto & ".png")
        ElseIf File.Exists(ruta_programa & "\Fotos\" & producto & ".jpg") Then
            bmp = New Bitmap(ruta_programa & "\Fotos\" & producto & ".jpg")
        End If

        Return bmp
    End Function

    Public Function Valida_Imagen(ByVal producto As String) As Boolean
        Return File.Exists(ruta_programa & "\Fotos\" & producto & ".png")
    End Function

    Public Sub Imprime_Pedido(ByVal pedido As String, Optional ByVal vista_previa As Boolean = False)
        documento = New PrintDocument
        previo = New Windows.Forms.PrintPreviewDialog

        iPedido = pedido

        Dim cantidad As Integer = dsData.Tables("PRODUCTOS").Select("REFER='" & iPedido & "'").Count

        If cantidad > 0 Then
            AddHandler documento.PrintPage, AddressOf Imp_Ped

            Dim pr As Integer
            pr = documento.PrinterSettings.PrinterResolutions.Count

            documento.DefaultPageSettings.PrinterResolution = documento.PrinterSettings.PrinterResolutions.Item(pr - 1)
            documento.DefaultPageSettings.Color = False


            documento.PrinterSettings.PrinterName = Valor_Config("EMPRESA", "Impresora Tickets")

            documento.DefaultPageSettings.Landscape = False

            If Valor_Config("EMPRESA", "Vista Previa") = "Si" Or vista_previa = True Then
                previo.Document = documento
                previo.ShowDialog()
            Else
                documento.Print()
            End If
        Else
            msg.Mostrar("Nada que imprimir", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If


    End Sub

    Public Sub Imp_Ped(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
        'e.Graphics.Clear(Color.Transparent)
        Dim margen As Integer = 10
        Dim margen2 As Integer = documento.DefaultPageSettings.PrintableArea.Width '- margen
        Dim alto As Integer = 10
        Dim altura As Integer = 10
        Dim fuente As New Font("Calibri", altura, FontStyle.Regular)
        Dim sf As New StringFormat

        Dim pedido As DataRow = dsData.Tables("FACTURAS").Select("REFER='" & iPedido & "'").GetValue(0)

        e.Graphics.DrawImage(New Bitmap(ruta_programa & "\Fotos\SIA.png"), New Rectangle(margen, alto, 32, 32))
        sf.Alignment = StringAlignment.Near
        e.Graphics.DrawString(Valor_Config("EMPRESA", "Nombre"), fuente, Brushes.Black, margen + 35, alto, sf)
        alto += altura + 3
        e.Graphics.DrawString(CType(dsInfo.Tables("CLIENTES").Select("CCLIE='" & pedido("CCLIE") & "'")(0), DataRow)(1), New Font("Calibri", altura + 1, FontStyle.Italic), Brushes.Black, margen + 35, alto, sf)

        alto += 20

        Dim cCant As Integer = margen
        Dim cArticulo As Integer = margen + 35
        Dim cTotal As Integer = margen2


        'alto += altura + 3
        'e.Graphics.DrawString(CType(dsInfo.Tables("CLIENTES").Select("CCLIE='" & pedido("CCLIE") & "'")(0), DataRow)(1), New Font("Calibri", altura + 1, FontStyle.Italic), Brushes.Black, margen, alto, sf)
        'alto += altura + 3
        alto += altura + 3
        sf.Alignment = StringAlignment.Near
        e.Graphics.DrawString("Cliente:", New Font("Calibri", altura, FontStyle.Bold), Brushes.Black, margen, alto, sf)
        e.Graphics.DrawString(pedido("CCLIE"), New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, margen + 50, alto, sf)
        sf.Alignment = StringAlignment.Far
        e.Graphics.DrawString("Fecha:", New Font("Calibri", altura, FontStyle.Bold), Brushes.Black, margen2 - 75, alto, sf)
        e.Graphics.DrawString(pedido("FECHA"), New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, margen2, alto, sf)
        alto += altura + 3

        sf.Alignment = StringAlignment.Near
        e.Graphics.DrawString("Pedido:", New Font("Calibri", altura, FontStyle.Bold), Brushes.Black, margen, alto, sf)
        e.Graphics.DrawString(pedido("REFER"), New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, margen + 50, alto, sf)
        sf.Alignment = StringAlignment.Far
        e.Graphics.DrawString("Fecha:", New Font("Calibri", altura, FontStyle.Bold), Brushes.Black, margen2 - 75, alto, sf)
        e.Graphics.DrawString(pedido("ENTREGA"), New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, margen2, alto, sf)
        'alto += altura + 3
        'e.Graphics.DrawString("Entrega:", New Font("Calibri", altura, FontStyle.Bold), Brushes.Black, margen, alto, sf)
        'e.Graphics.DrawString(pedido("FECHA"), New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, margen + 75, alto, sf)
        'alto += altura + 3
        'e.Graphics.DrawString("Entrega:", New Font("Calibri", altura, FontStyle.Bold), Brushes.Black, margen, alto, sf)
        'e.Graphics.DrawString(pedido("ENTREGA"), New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, margen + 75, alto, sf)

        alto += altura + 3
        alto += altura + 3
        sf.Alignment = StringAlignment.Center
        If pedido("TIPO") = "X" Then
            e.Graphics.DrawString("COMPRA DE CONTADO", New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, documento.DefaultPageSettings.PrintableArea.Width / 2, alto, sf)
        Else
            e.Graphics.DrawString("COMPRA A CREDITO", New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, documento.DefaultPageSettings.PrintableArea.Width / 2, alto, sf)
        End If



        alto += altura + 3
        alto += altura + 3
        sf.Alignment = StringAlignment.Near
        e.Graphics.DrawString("#", New Font("Calibri", altura, FontStyle.Bold), Brushes.Black, cCant, alto, sf)
        e.Graphics.DrawString("Articulo", New Font("Calibri", altura, FontStyle.Bold), Brushes.Black, cArticulo, alto, sf)
        sf.Alignment = StringAlignment.Far
        e.Graphics.DrawString("Subtotal", New Font("Calibri", altura, FontStyle.Bold), Brushes.Black, cTotal, alto, sf)

        alto += altura + 7
        e.Graphics.DrawLine(Pens.Black, margen, alto, margen2, alto)

        alto += 2

        Dim dtImpresion As New DataTable(iPedido)
        dtImpresion = dsData.Tables("PRODUCTOS").Clone

        For Each fila As DataRow In dsData.Tables("PRODUCTOS").Select("REFER='" & iPedido & "'")
            dtImpresion.ImportRow(fila)
        Next

        Sort(dtImpresion, "LINEA")
        Dim tmpLinea As String = ""
        Dim c As Integer = 0

        For Each fila As DataRow In dtImpresion.Rows
            sf.Alignment = StringAlignment.Near

            If tmpLinea <> fila("LINEA") Then
                If c > 0 Then alto += altura + 5
                e.Graphics.DrawString(fila("LINEA"), New Font("Calibri", altura, FontStyle.Bold), Brushes.Black, cCant, alto, sf)
                alto += altura + 5
                tmpLinea = fila("LINEA")
                c += 1
            End If

            e.Graphics.DrawString(fila("CANTIDAD"), New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, cCant, alto, sf)
            'e.Graphics.DrawString(fila("ARTICULO"), New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, cArticulo, alto, sf)
            e.Graphics.DrawString(fila("DESCRIPCION").ToString.Trim.Substring(0, Math.Min(35, fila("DESCRIPCION").ToString.Trim.Length)), New Font("Calibri", altura - 3, FontStyle.Bold), Brushes.Black, cArticulo, alto + 4, sf)

            sf.Alignment = StringAlignment.Far
            e.Graphics.DrawString(Format(Val(fila("IMPORTE")) * Val(fila("CANTIDAD")), "$ ###,###,##0.00"), New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, cTotal, alto, sf)
            'alto += altura + 4

            'sf.Alignment = StringAlignment.Near
            'e.Graphics.DrawString("(" & fila("DESCRIPCION") & ")", New Font("Calibri", altura - 3, FontStyle.Italic), Brushes.Black, cCant, alto, sf)
            'alto += altura + 3
            'alto += altura + 3

            alto += altura + 5
        Next

        alto += 2
        e.Graphics.DrawLine(Pens.Black, margen, alto, margen2, alto)
        alto += 2
        e.Graphics.DrawLine(Pens.Black, margen, alto, margen2, alto)
        alto += altura + 3

        sf.Alignment = StringAlignment.Far
        e.Graphics.DrawString("Subtotal:", New Font("Calibri", altura, FontStyle.Bold), Brushes.Black, margen2 - 100, alto, sf)
        e.Graphics.DrawString(Format(pedido("SUBTOTAL"), "$ ###,###,##0.00"), New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, margen2, alto, sf)
        alto += altura + 3
        e.Graphics.DrawString("IVA:", New Font("Calibri", altura, FontStyle.Bold), Brushes.Black, margen2 - 100, alto, sf)
        e.Graphics.DrawString(Format(pedido("IVA"), "$ ###,###,##0.00"), New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, margen2, alto, sf)
        alto += altura + 3
        e.Graphics.DrawString("Total:", New Font("Calibri", altura, FontStyle.Bold), Brushes.Black, margen2 - 100, alto, sf)
        e.Graphics.DrawString(Format(pedido("TOTAL"), "$ ###,###,##0.00"), New Font("Calibri", altura, FontStyle.Regular), Brushes.Black, margen2, alto, sf)
        alto += altura + 3

        alto += altura + 3
        alto += altura + 3
        sf.Alignment = StringAlignment.Near
        e.Graphics.DrawString("Impresion:", New Font("Calibri", altura - 3, FontStyle.Bold), Brushes.Black, margen, alto, sf)
        sf.Alignment = StringAlignment.Far
        e.Graphics.DrawString(Format(Now, "dd/MM/yyyy HH:mm:ss"), New Font("Calibri", altura - 3, FontStyle.Regular), Brushes.Black, margen2, alto, sf)

        alto += altura + 2
        sf.Alignment = StringAlignment.Near
        e.Graphics.DrawString("Atendió:", New Font("Calibri", altura - 3, FontStyle.Bold), Brushes.Black, margen, alto, sf)
        sf.Alignment = StringAlignment.Far
        e.Graphics.DrawString(Valor_Config("EMPRESA", "Nombre del Vendedor"), New Font("Calibri", altura - 3, FontStyle.Regular), Brushes.Black, margen2, alto, sf)
    End Sub

    Private Sub Sort(ByRef dtTable As DataTable, ByVal Column As String)
        Dim DV As New DataView(dtTable)
        DV.Sort = Column
        dtTable = DV.ToTable(dtTable.TableName)
    End Sub
End Module
